const request=require("superagent");
const FormData = require('form-data');
const https = require('https');
const cheerio = require('cheerio');
const iconv = require('iconv-lite');
const util = require('util');
const charset = require("superagent-charset")(request);
const fs=require('fs');
var mysql      = require('mysql');
const assert = require('assert');
var connection = mysql.createConnection({
  host     : '127.0.0.1',
  user     : 'root',
  password : '123456',
  database : 'hn_matter'
});
connection.query = util.promisify(connection.query);
async function getResourceTree(page) {
    var resource = await page._client.send('Page.getResourceTree');
    return resource.frameTree;
}

async function getResourceContent(page, url) {
    const { content, base64Encoded } = await page._client.send(
        'Page.getResourceContent',
        { frameId: String(page.mainFrame()._id), url },
    );
    assert.equal(base64Encoded, true);
    return content;
};
const Agent=[
 	"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
    "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    "MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    "JUC (Linux; U; 2.3.7; zh-cn; MB200; 320*480) UCWEB7.9.3.103/139/999",
    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0a1) Gecko/20110623 Firefox/7.0a1 Fennec/7.0a1",
    "Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10",
    "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
    "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3",
    "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7",
    "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10",
    "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+",
    "Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0",
    "Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/20.0.019; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.18124",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)",
    "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36",
];
const timeout={
	response:50000,
	deadline:600000,
}
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
function delay(t){
    return new Promise(resolve => setTimeout(resolve, t))
}

function rnd(n, m){
    var random = Math.floor(Math.random()*(m-n+1)+n);
    return random;
}
function getRndIP(){
    var ip=[];
    for(var i=0;i<4;i++){
    ip.push(rnd(10,250));
    }
    return ip.join(".");
}

const agent_c = new https.Agent({
  rejectUnauthorized: false
});

// process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
//封装请求 实现失败重试
async function requestWithRetry(url, retryCount = 3, timeout = 5000,option,data='') {
  return new Promise((resolve, reject) => {
    let numRetries = 0;
 
    const makeRequest = () => {
      request
        .post(url)
        .set(option)
        .agent(agent_c)
        .timeout(timeout) // 设置超时时间
        .field('id', data)//模拟form-data
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          if ((error.code === 'ECONNABORTED'||error.code === 'ECONNRESET') && numRetries < retryCount) {
            numRetries += 1;
            console.log(`Request timed out. Retrying... (Attempt ${numRetries})`);
            makeRequest(); // 重试请求
          } else {
            reject(error);
          }
        });
    };
 
    makeRequest();
  });
}
async function getArea(){
    let level_i = 4;
    let sql=`select * from m_area where id > 1227 AND level = `+level_i;
        let result=await connection.query(sql);
        for (var i = 0; i < result.length; i++) {
            var ip=getRndIP();
            var agent=Agent[rnd(0,Agent.length-1)];
            agent=Agent[0];
            var option={
                "Host":"wssp.hainan.gov.cn",
                "User-Agent":agent,
                "Referer":'https://wssp.hainan.gov.cn/',
                "X-Forwarded-For":ip,
            }
            let url=`https://wssp.hainan.gov.cn/wssp3/address/exempt/getAddress?deptId=`+result[i]['id_w'];
            console.log(result[i]['id'],result[i]['name'],url);
            let res = await requestWithRetry(url, 10, 5000,option).then(response => {
                // console.log('Response received:', response);
                return response;
              }).catch(error => {
                console.error('Error:', error);
              });

            let resData1 = JSON.parse(res.text).data.horizonDeptList;
            let resData2 = JSON.parse(res.text).data.introductionParkList;

            let resData = resData1.concat(resData2);
            if(resData.length==0){

            console.log('无数据')
            }
            for (var j = 0; j < resData.length; j++) {
                await asySql("INSERT INTO m_area SET  ?",{
                        'pid' : result[i]['id'],
                        'code' : resData[j]['deptCode'],
                        'name' : resData[j]['deptName'],
                        'level' : level_i+1,
                        'id_w': resData[j]['id']
                    }).then(insertId => {
                        return insertId;
                    }).catch(error => {
                      console.error(error); // 异步操作失败，输出错误信息
                    });
            }
            await delay(500);
            
        }
    		
}

async function getUnit(){
    let serverType = 1;
    let sql=`select * from m_area where id > 0 AND pid = 26`;
    let result=await connection.query(sql);
    for (var i = 0; i < result.length; i++) {
            var ip=getRndIP();
            var agent=Agent[rnd(0,Agent.length-1)];
            agent=Agent[0];
            var option={
                "Host":"wssp.hainan.gov.cn",
                "User-Agent":agent,
                "Referer":'https://wssp.hainan.gov.cn/',
                "X-Forwarded-For":ip,
            }
            let url=`https://wssp.hainan.gov.cn/wssp3/zwgk/department?deptId=${result[i]['id_w']}&type=${serverType}`;
            console.log(result[i]['id'],result[i]['name'],url);
            let res = await requestWithRetry(url, 3, 5000,option).then(response => {
                // console.log('Response received:', response);
                return response;
              }).catch(error => {
                console.error('Error:', error);
              });
            let resData = JSON.parse(res.text).data;
            // console.log(resData)
            for (var j = 0; j < resData.length; j++) {
                let checkResult = await connection.query(`select * from m_unit where area_id = '${result[i]['id']}' AND name = '${result[i]['name']}'`);
                    if(checkResult.length>0){
                        console.error('数据已存在', resData[j]['bm_name']);
                    }else{
                        await asySql("INSERT INTO m_unit SET  ?",{
                            'area_id' : result[i]['id'],
                            'code' : resData[j]['bm_id'],
                            'name' : resData[j]['bm_name']
                        }).then(insertId => {
                            return insertId;
                        }).catch(error => {
                          console.error(error); // 异步操作失败，输出错误信息
                        });
                    }
            }
            
            await delay(1000);
            
        }
        
          
process.exit(0);  
}

async function getMatterList(){
    let serverType = 1;
    let sql=`select * from m_area where id > 0 AND id = 26`;
    let result=await connection.query(sql);
    for (var i = 0; i < result.length; i++) {

        for (var pageNumber = 1; pageNumber <= 999; pageNumber++) {
            var ip=getRndIP();
            var agent=Agent[rnd(0,Agent.length-1)];
            agent=Agent[0];
            var option={
                "Host":"wssp.hainan.gov.cn",
                "User-Agent":agent,
                "Referer":'https://wssp.hainan.gov.cn/',
                "X-Forwarded-For":ip,
                "Content-Type":"multipart/form-data;"
            }
            // let url=`https://wssp.hainan.gov.cn/wssp3/matter/exempt/info`;
            let url=`https://wssp.hainan.gov.cn/wssp3/matter/exempt/townshipMatter`;
            console.log('page:',pageNumber,result[i]['id'],result[i]['name']);
            let res = await requestWithRetry(url, 3, 5000,option,`{"regionId":"${result[i]['id_w']}","qdCategory":"pcSxQd","pageNumber":${pageNumber},"pageSize":10}`).then(response => {
                // console.log('Response received:', response);
                return response;
              }).catch(error => {
                console.error('Error:', error);
              });
              // console.log(JSON.parse(res.text))
            let resData = JSON.parse(res.text).data.townshipMatterList;

            if(resData.length==0){
                console.log('无数据')
                pageNumber = 1000;
                continue;
            }
             for (var j = 0; j < resData.length; j++) {

            console.log('无数据')
                //部门数据
                let unitResult = await connection.query(`select * from m_unit where name = '${resData[j]['subdatas'][0]['deptname']}' AND area_id='${result[i]['id']}'`);
                 // console.log(unitResult[0]['full_name'])
                let unit_id = 0;
                //判断部门是否已存在
                if(unitResult.length>0){
                    //存在
                    //判断部门全称是否存在
                    // if(unitResult[0]['full_name']==null){
                    //     //不存在 插入部门全称
                    //     console.log('插入部门全称',resData[j]['OrgName'])
                    //     await connection.query(`update m_unit SET full_name = '${resData[j]['OrgName']}' where id = '${unitResult[0]['id']}'`);
                    // }
                    unit_id = unitResult[0]['id'];
                }else{
                    //不存在 插入部门
                    console.log('插入部门',resData[j]['subdatas'][0]['deptname'])
                    let addSql="INSERT INTO m_unit SET  ?";
                    let addSqlParams = {
                        'area_id':result[i]['id'],
                        'name':resData[j]['subdatas'][0]['deptname'],
                        'code':resData[j]['subdatas'][0]['deptcode']
                    };
                    unit_id = await asySql(addSql,addSqlParams).then(insertId => {
                        return insertId;
                    }).catch(error => {
                      console.error(error); // 异步操作失败，输出错误信息
                    });

                }
                if(unit_id>0){
                    //事项目录
                    let directory_id = 0;
                    let directoryResult = await connection.query(`select * from m_matter_directory where name = '${resData[j]['taskname']}' AND area_id='${result[i]['id']}'`);
                    if(directoryResult.length>0){
                        directory_id = directoryResult[0]['id'];
                        console.error('目录数据已存在', directoryResult[0]['name']);
                    }else{
                        directory_id = await asySql("INSERT INTO m_matter_directory SET  ?",{
                                'taskcode' : resData[j]['taskcode'],
                                'name' : resData[j]['taskname'],
                                'area_id': result[i]['id'],
                                'unit_id': unit_id
                            }).then(insertId => {
                                return insertId;
                            }).catch(error => {
                              console.error(error); // 异步操作失败，输出错误信息
                            });
                    }
                    let itemList = resData[j]['subdatas'];
                    //事项列表
                    for(var k = 0; k < itemList.length; k++) {
                        let checkResult = await connection.query(`select * from m_matter where name = '${itemList[k]['taskname']}' AND area_id='${result[i]['id']}'`);
                        if(checkResult.length>0){
                            console.error('事项数据已存在', checkResult[0]['name']);
                        }else{
                            await asySql("INSERT INTO m_matter SET  ?",{
                                    'm_id':itemList[k]['id'],
                                    'sourcekey' : itemList[k]['sourcekey'],
                                    'implement_code': itemList[k]['taskcode'],
                                    'name':itemList[k]['taskname'],
                                    'directory_id':directory_id,
                                    'area_id': result[i]['id'],
                                    'unit_id': unit_id,
                                    'service_type':serverType
                                }).then(insertId => {
                                    return insertId;
                                }).catch(error => {
                                  console.error(error); // 异步操作失败，输出错误信息
                                });
                        }
                    }


                }
            }
            //随机0.5到2.5秒请求时间间隔 防止屏蔽
            let ran = Math.floor(Math.random() * 2000) + 500;
            console.log(ran);
            await delay(ran);
        }
            
    }
        
          
process.exit(0);  
}

async function getMatterInfo(){
    let sql=`select * from m_matter where id > 0 and base_code is null`;
    let result=await connection.query(sql);
    for (var i = 0; i < result.length; i++) {
        var ip=getRndIP();
        var agent=Agent[rnd(0,Agent.length-1)];
        agent=Agent[0];
        var option={
            "Host":"wssp.hainan.gov.cn",
            "User-Agent":agent,
            "Referer":'https://wssp.hainan.gov.cn/',
            "X-Forwarded-For":ip,
        }
        let url=`https://wssp.hainan.gov.cn/wssp3/bszn/exempt/allInfo`;
        console.log(result[i]['id'],result[i]['name'],url);
        let res = await requestWithRetry(url, 3, 5000,option,result[i]['m_id']).then(response => {
            return response;
          }).catch(error => {
            console.error('Error:', error);
          });
        let resData = JSON.parse(res.text).data;
        if(resData==null){
            console.log('数据错误，跳过');
            continue;
        }
        if(resData.length==0){
            console.log('无数据')
            return
        }
        if(resData['sxImplBasic']==undefined){
            console.log('数据错误，跳过');
            continue;
        }

        //服务对象
        let service_object = resData['sxImplBasic']['servertypename'];
        if(service_object.indexOf(';')){
        service_object = service_object.split(";");
        }else{
            service_object = service_object.split(",");
        }
        for (var s_i = 0; s_i < service_object.length; s_i++) {
            if(service_object[s_i] == '自然人'){
                service_object[s_i] = 1;
            }else if(service_object[s_i]=='事业法人'){
                service_object[s_i] = 2;
            }else if(service_object[s_i]=='企业法人'){
                service_object[s_i] = 3;
            }else if(service_object[s_i]=='非法人企业'){
                service_object[s_i] = 4;
            }else if(service_object[s_i]=='行政机关'){
                service_object[s_i] = 5;
            }else if(service_object[s_i]=='社会组织法人'){
                service_object[s_i] = 6;
            }else if(service_object[s_i]=='其它组织'||service_object[s_i]=='其他组织'){
                service_object[s_i] = 7;
            }else{
                console.error('未找到服务对象：'+service_object[s_i])
                return;
            }
        }
        service_object = service_object.join(",");
        //办件类型
        let processing_type = resData['sxImplBasic']['projecttypename'];
        if(processing_type=='承诺件'){
            processing_type = 1;
        }else if(processing_type=='即办件'){
            processing_type = 2;
        }else{
            console.error('未找到办件类型：'+processing_type)
            return;
        }

        //事项类型
        let event_type = resData['sxImplBasic']['tasktypename'];
        if(event_type=='行政许可'){
            event_type = 1;     
        }else if(event_type=='行政给付'){
            event_type = 2;
        }else if(event_type=='行政确认'){
            event_type = 3;
        }else if(event_type=='行政奖励'){
            event_type = 4;
        }else if(event_type=='行政裁决'){
            event_type = 5;
        }else if(event_type=='行政备案'){
            event_type = 6;
        }else if(event_type=='其它行政权力'||event_type=='其他行政权力'||event_type=="行政征收"){
            event_type = 7;
        }else if(event_type=='公共服务'){
            event_type = 8;
        }else{
            console.error('未找到事项类型：'+event_type)
            return;
        }
        //实施主体性质
        let implement_subject_nature = resData['sxImplBasic']['depttypename'];
        if(implement_subject_nature=='法定机关'){
            implement_subject_nature = 1;
        }else if(implement_subject_nature=='授权组织'){
            implement_subject_nature = 2;
        }else if(implement_subject_nature=='受委托组织'){
            implement_subject_nature = 3;
        }else{
            console.error('未找到实施主体性质：'+implement_subject_nature)
            return;
        }

         data = {
                    'arrive_num':resData['sxImplBasic']['limitscenenum'],//到场次数
                    'legal_time':resData['sxImplBasic']['anticipateday'],//法定时限
                    'promise_time':resData['sxImplBasic']['promiseday'],//承诺时限
                    'implement_subject':resData['sxImplBasic']['deptname'],//实施主体
                    'implement_subject_code':resData['sxImplBasic']['deptcode'],//实施主体编码
                    'service_object':service_object,//服务对象
                    'processing_type':processing_type,//办件类型
                    'transactaddr':resData['sxImplBasic']['transactaddr'],//办理地点
                    'transacttime':resData['sxImplBasic']['transacttime'],//办理时间
                    'linkway':resData['sxImplBasic']['linkway'],//咨询方式
                    'superviseway':resData['sxImplBasic']['superviseway'],//监督投诉方式
                    'event_type':event_type,//事项类型
                    'base_code':resData['sxImplBasic']['catalogcode'],//基本编码
                    'implement_subject_nature':implement_subject_nature,//实施主体性质
                    'joint_agency':resData['sxImplBasic']['otherdept'],//联办机构
                    'is_entry':resData['sxImplBasic']['isentrycenter'],//是否进驻政务大厅
                    'is_self_service':resData['sxImplBasic']['isserviceterminals'],//是否支持自助终端办理
                    'is_online_office':resData['sxImplBasic']['isonline'],//是否网办
                    'application_form':resData['sxImplBasic']['handletypename'],//办理形式
                    'is_reservation':resData['sxImplBasic']['isschedule'],//是否支持预约办理
                    'approval_result_type':resData['sxImplBasic']['resulttypename'],//审批结果类型
                    'approval_result_name':resData['sxImplBasic']['resultname'],//审批结果名称
                    'is_express_delivery':resData['sxImplBasic']['isexpress'],//是否支持物流快递
                }
        
        
        await asySql(`update m_matter SET ? where id = '${result[i]['id']}'`,data).then(insertId => {
            return insertId;
        }).catch(error => {
          console.error(error); // 异步操作失败，输出错误信息
        });

        //通用情形
        let case_id = 0;
        let result_case=await connection.query(`select id from m_matter_case WHERE matter_id='${result[i]["id"]}'`);
        if(result_case.length>0){
            case_id = result_case[0]['id'];
        }else{
            case_id = await asySql("INSERT INTO m_matter_case SET  ?",{
                        'pid':0,
                        'matter_id':result[i]['id'],
                        'name':'通用情形'
                    }).then(insertId => {
                        return insertId;
                    }).catch(error => {
                      console.error(error); // 异步操作失败，输出错误信息
                    });
        }


        if(case_id>0){
            //材料列表
            if(resData['materials']!=null){
                let workApplyData = resData['materials'];
                for (var w = 0; w < workApplyData.length; w++) {
                    let sql=`select * from m_matter_material WHERE name='${workApplyData[w].materialname}' AND case_id='${case_id}'`;
                    let result_material=await connection.query(sql);
                    if(result_material.length>0){
                        console.log('材料已录入',case_id,workApplyData[w].materialname);
                    }else{
                        //来源渠道
                        let source = workApplyData[w].sourcetype;
                        let source_info = workApplyData[w].sourceexplain;
                        if(source==10){
                            //申请人自备
                            source = 1;
                        }else if(source==20){
                            //政府部门核发
                            source = 2;
                        }else if(source==99||source == ''){
                            //其它
                            source = 3;
                        }else{
                            console.log('找不到来源渠道',source)
                            return;
                        }
// materialformat 
// 1纸质 2电子 3纸质和电子 4纸质或电子

// materialtype 
// 1原件 2复印件
                        // //类型
                        let type = workApplyData[w].materialtype;
                        if(type>3){
                            console.log('找不到类型',type)
                            return;
                        }
                        if(!type){
                            type = 0;
                        }
                        // if(type=='原件'){
                        //     type = 1;
                        // }else if(type=='复印件'){
                        //     type = 2;
                        // }else if(type=='原件和复印件'){
                        //     type = 3;
                        // }else if(type=='电子版'){
                        //     type = 4;
                        // }else{
                        //     console.log('找不到类型',type)
                        //     return;
                        // }

                        // //形式
                        let shape = workApplyData[w].materialformat;
                        // if(shape=='纸质'){
                        //     shape = 1;
                        // }else if(shape=='电子'){
                        //     shape = 2;
                        // }else if(shape=='纸质、电子'||shape=='纸质和电子'){
                        //     shape = 3;
                        // }else if(shape=='纸质或电子'){
                        //     shape = 4;
                        // }else if(shape==''){
                        //     shape = null;
                        // }else{
                        //     console.log('找不到形式',shape)
                        //     return;
                        // }

                        //必要性
                        let necessity = workApplyData[w].isneed;
                        if(necessity=='1'){
                            necessity = 1;
                        }else if(necessity=='2'){
                            necessity = 2;
                        }else if(necessity=='3'){

                            //  容缺后补
                            necessity = 4;
                        }else if(necessity==''){

                            // 
                            necessity = 1;
                        }else{
                            console.log('找不到必要性',necessity)
                            return;
                        }

                        let addSql="INSERT INTO m_matter_material SET  ?";
                        let addSqlParams = {
                            'case_id':case_id,
                            'MaterialCode':workApplyData[w].id,
                            'name':workApplyData[w].materialname,
                            'type':type,
                            'shape':shape,
                            'number':workApplyData[w].pagenum,
                            'copy_number':workApplyData[w].pagenum,
                            'necessity':necessity,
                            'source':source,
                            'source_info':source_info,
                            'standard':workApplyData[w].acceptstand,
                            'notice':workApplyData[w].fillexplain,
                            'bylaw':workApplyData[w].bylaw,
                            'pageformat':workApplyData[w].pageformat,
                        };
                        await asySql(addSql,addSqlParams).then(insertId => {
                            return insertId;
                        }).catch(error => {
                          console.error(error); // 异步操作失败，输出错误信息
                        });
                    }
                }
            }
            
        }
        //常见问题
        for (var q = 0; q < resData['questions'].length; q++) {
            let question = resData['questions'][q]['question'];
            let answer = resData['questions'][q]['answer'];
            answer = filterHTMLTags(answer);
            let result_question = await connection.query(`select id from m_matter_question WHERE matter_id='${result[i]["id"]}' AND questions='${question}'`);
            if(result_question.length>0){
                console.log('常见问题已录入')
            }else{
                await asySql(`INSERT INTO m_matter_question SET ?`,{
                    'matter_id':result[i]["id"],
                    'questions':question,
                    'answers':answer
                }).then(insertId => {
                    return insertId;
                }).catch(error => {
                  console.error(error); // 异步操作失败，输出错误信息
                });
            }
        }
                        
        //随机0.5到2.5秒请求时间间隔 防止屏蔽
        let ran = Math.floor(Math.random() * 2000) + 500;
        console.log(ran);
        await delay(ran);
    }
    process.exit(0); 
}

//插入数据库
async function asySql(addSql,addSqlParams){
    return await new Promise(resolve => {
        connection.query(addSql,addSqlParams,function (err, result) {
            if(err){
             console.log('[INSERT ERROR] - ',err.message);
             return;
            }else{
                console.log('INSERT ID:',result.insertId);
                return resolve(result.insertId);
            }        
            
        });
    })
        
}

function filterHTMLTags(str) {
  return str.replace(/<[^>]*>/g, '');
}


//海南省区域
// getArea();

//部门 已获取：陵水县、海南省、海口市、琼山区及其下属乡镇
// getUnit();

//事项列表 已获取：陵水县、海南省、海口市、琼山区及其下属乡镇
//行为非法被拒 需开启.field('qrys', data)//模拟form-data并改为post请求
// getMatterList();
//事项详情
getMatterInfo();

// async function DelUnit(){
//     let result=await connection.query(`select * from m_unit`);
//     for (var i = 0; i < result.length; i++) {
//         let result_question = await connection.query(`select id from m_matter WHERE unit_id='${result[i]["id"]}'`);
//             if(result_question.length==0){
//                  await connection.query(`delete from m_unit WHERE id='${result[i]["id"]}'`);
//             }
        
//     }
// }

// DelUnit();